package com.itxh.reader;

import com.itxh.factory.DefaultListableBeanFactory;
import com.itxh.registry.BeanDefinitionRegistry;
import com.itxh.resource.ClasspathResource;
import com.itxh.resource.Resource;
import com.itxh.utils.DocumentUtils;
import org.dom4j.Document;

import java.io.InputStream;

/**
 * 该类的职责是制定如何加载BeanDefinition的流程
 */
public class XmlBeanDefinitionReader implements BeanDefinitionReader{
    private BeanDefinitionRegistry beanDefinitionRegistry ;

    public XmlBeanDefinitionReader(DefaultListableBeanFactory beanFactory) {
        this.beanDefinitionRegistry = beanFactory;
    }

    @Override
    public void loadBeanDefinitions(Resource resource) {
        InputStream inputStream = resource.getInputStream();
        // 将流数据转换为格式化数据Document
        Document document = DocumentUtils.createDocument(inputStream);

        BeanDefinitionDocumentReader documentReader = new BeanDefinitionDocumentReader(beanDefinitionRegistry);

        // 按照自定义spring语义去解析文档数据，最终将解析出来的BeanDefinition存储到集合中
        documentReader.parseBeanDefinitions(document.getRootElement());
    }

    @Override
    public void loadBeanDefinitions(String location) {
        Resource resource = new ClasspathResource(location);
        this.loadBeanDefinitions(resource);
    }
}
